package fr.inria.arles.tempManagement.RFID;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import fr.inria.arles.temperatureManagement.*;
import java.util.Collection;
import static fr.inria.arles.temperatureManagement.Constants.*;
import fr.inria.arles.temperatureManagement.QueryException;
import fr.inria.arles.tempmanagement.preferencesstore.service.Exception_Exception;
import fr.inria.arles.tempmanagement.preferencesstore.service.QueryPort;
import fr.inria.arles.tempmanagement.preferencesstore.service.QueryPort_Service;

/**
 *
 * @author pret-miriad
 */
public class RFIDProcessor {

    private static void actuate(String partition, Collection<Double> values)
            throws IOException, QueryException, ProcessingNodeConnectionFailureException {
        Double avg = 0.0;
        if (values.size() == 0) {
            avg = DEFAULT_TEMP_SETTING;
        } else {
            for (Double x : values) {
                avg += x;
            }
            avg /= values.size();
        }

        ProcessingNodeCommunicator.updateTemp(PROCESSING_NODE_IP,
                PROCESSING_NODE_PORT,
                partition, avg + "");
        System.out.println("Temperature Setting Updated To:" + avg);
    }
    private static Map<String, HashMap<String, Double>> settings =
            new HashMap<String, HashMap<String, Double>>();

    static void processRFID(String RFID, String partition)
            throws UnknownHostException, IOException, QueryException,
            ProcessingNodeConnectionFailureException {
        Double temp;
        HashMap<String, Double> currentPartitonSettings = settings.get(partition);
        if (currentPartitonSettings == null) {
            currentPartitonSettings = new HashMap<String, Double>();
            settings.put(partition, currentPartitonSettings);
        }
        if ((temp = currentPartitonSettings.get(RFID)) != null) {
            currentPartitonSettings.remove(RFID);
            System.out.println("User with RFID tag " + RFID
                    + " and Temperature Setting:" + temp + " has EXITED");
            actuate(partition, currentPartitonSettings.values());
        } else {
            try {
                QueryPort_Service service = new QueryPort_Service();
                QueryPort port = service.getQueryPortPort();
                
                String ID = port.rfidQuery(RFID, partition);
                temp = (double)port.getTempQuery(ID);
                System.out.println("User with RFID tag " + RFID
                        + " and Temperature Setting:" + temp + " has ENTERED");
                currentPartitonSettings.put(RFID, temp);
                actuate(partition, currentPartitonSettings.values());
            } catch (Exception_Exception ex) {                                
                throw new QueryException(ex.getFaultInfo().getMessage());
            }

        }
    }
}
